<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Matches extends MY_Controller {

	private $now; 
	private $matchgroups;
	private $teams;

	function Matches() {
		parent::MY_Controller();

    	$this->ci =& get_instance();

		$this->now = date("Y-m-d H:i:s");
		
		$sql = "SELECT DISTINCT matchgroup as name FROM ".$this->tblm;
		$query = $this->db->query($sql);
		$this->matchgroups = $this->getGroups($query->result());

		$sql = "SELECT DISTINCT name, three FROM ".$this->tblx." ORDER BY name";
		$query = $this->db->query($sql);
		$this->teams = $query->result();
		
	}

	function index() {
		$data = $this->getData('matches');

		// Wenn ein Spieltag läuft sollte dieser angezeigt werden.
		// Wenn kein Spieltag läuft sollte der der alte und der neue angezeigt werden, wenn es beide gibt
		$lastGroup = $this->getLastGroup();
		$nextGroup = $this->getNextGroup();
		
		if ($lastGroup === null) $lastGroup = $nextGroup;
		if ($nextGroup === null) $nextGroup = $lastGroup; 

		$attribs = "tm.id, tm.team_h, tm.team_a, tm.goals_h, tm.goals_a,tm.deadline, tm.matchgroup, tm.place, "
			."tmh.short as team_h_short,tmh.three as team_h_three,tma.short as team_a_short,tma.three as team_a_three";
		
		
		$sql = "SELECT ".$attribs." FROM ".$this->tblm." as tm, ".$this->tblx." as tmh, ".$this->tblx." as tma"
			." WHERE tm.team_h = tmh.name AND tm.team_a = tma.name"
			." AND (matchgroup = ? OR matchgroup = ?)"
			." ORDER BY deadline";

		$query = $this->db->query($sql, array($lastGroup, $nextGroup));	
		
		$matches = $query->result();
		$this->fillMatches($matches);
		
		$redirect = 'matches';
		$data["redirect"] = $redirect;
		
		$d['userselection'] = $this->load->view('selection-user', $this->getUser($redirect), true);
		$d['isOwner'] = $this->isOwner;
		$d['matches'] = $matches;
		$d['matchgroup'] = 'current';
		
		$d['matchgroups'] = $this->matchgroups;
		$d['teams'] = $this->teams;
		$d['teamselected'] = "";
		
		$data["content"] = $this->load->view('matches', $d, true);
		$this->load->view('layout', $data);
	}

	function day($id) {
		
		if (is_numeric($id))
			$id = intval("".$id);
			 
		$data = $this->getData('matches');		
		
		$attribs = "tm.id, tm.team_h, tm.team_a, tm.goals_h, tm.goals_a,tm.deadline, tm.matchgroup, tm.place, "
			."tmh.short as team_h_short,tmh.three as team_h_three,tma.short as team_a_short,tma.three as team_a_three";
		
		$sql = "SELECT ".$attribs." FROM ".$this->tblm." as tm, ".$this->tblx." as tmh, ".$this->tblx." as tma"
			." WHERE tm.team_h = tmh.name AND tm.team_a = tma.name"
			." AND matchgroup = ?"
			." ORDER BY deadline";

		$query = $this->db->query($sql, array($id));

		$matches = $query->result();
		$this->fillMatches($matches);
		
		
		$redirect = 'matches/day/'.$id;
		$data["redirect"] = $redirect;
		
		$d['userselection'] = $this->load->view('selection-user', $this->getUser($redirect), true);
		$d['isOwner'] = $this->isOwner;
		$d['matches'] = $matches;
		$d['matchgroup'] = $id;
		$d['matchgroups'] = $this->matchgroups;
		
		$d['teams'] = $this->teams;
		$d['teamselected'] = "";
		
		$data["content"] = $this->load->view('matches', $d, true);
		$this->load->view('layout', $data);
	}

	function all() {
		$data = $this->getData('matches');		
		
		$attribs = "tm.id, tm.team_h, tm.team_a, tm.goals_h, tm.goals_a,tm.deadline, tm.matchgroup, tm.place, "
			."tmh.short as team_h_short,tmh.three as team_h_three,tma.short as team_a_short,tma.three as team_a_three";
		
		$sql = "SELECT ".$attribs." FROM ".$this->tblm." as tm, ".$this->tblx." as tmh, ".$this->tblx." as tma"
			." WHERE tm.team_h = tmh.name AND tm.team_a = tma.name"
		." ORDER BY tm.deadline";
		
		$query = $this->db->query($sql);

		$matches = $query->result();
		$this->fillMatches($matches);
		
		$redirect = 'matches/all';
		$data["redirect"] = $redirect;
		
		$d['userselection'] = $this->load->view('selection-user', $this->getUser($redirect), true);
		$d['isOwner'] = $this->isOwner;
		$d['matches'] = $matches;
		
		
		
		$d['matchgroup'] = 'all';
		$d['matchgroups'] = $this->matchgroups;
		$d['teams'] = $this->teams;
		$d['teamselected'] = "";
		
		$data["content"] = $this->load->view('matches', $d, true);
		$this->load->view('layout', $data);
	}
	
	
	
	function team($team) {
		// TODO:: Zeige alle Spiele eines Teams
				
		$data = $this->getData('matches');

		$attribs = "tm.id, tm.team_h, tm.team_a, tm.goals_h, tm.goals_a,tm.deadline, tm.matchgroup, tm.place, "
			."tmh.short as team_h_short,tmh.three as team_h_three,tma.short as team_a_short,tma.three as team_a_three";
		
		$sql = "SELECT ".$attribs." FROM ".$this->tblm." as tm, ".$this->tblx." as tmh, ".$this->tblx." as tma"
			." WHERE tm.team_h = tmh.name AND tm.team_a = tma.name"
			." AND (tmh.three = ? OR tma.three = ?)"
			." ORDER BY tm.deadline";
		$query = $this->db->query($sql, array($team, $team));

		$matches = $query->result();
		$this->fillMatches($matches);
		
		$redirect = 'matches/all';
		$data["redirect"] = $redirect;
		
		$d['userselection'] = $this->load->view('selection-user', $this->getUser($redirect), true);
		$d['isOwner'] = $this->isOwner;
		$d['matches'] = $matches;
		$d['matchgroup'] = 'all';
		$d['matchgroups'] = $this->matchgroups;
		$d['teams'] = $this->teams;
		$d['teamselected'] = $team;
		
		$data["content"] = $this->load->view('matches', $d, true);
		$this->load->view('layout', $data);
	}


	function match($id) {
		$this->load->plugin('jpgraph');
		
		$data = $this->getData('matches');		
		
		$sql = "SELECT * FROM ".$this->tblm." WHERE id = ? LIMIT 1";
		$query = $this->db->query($sql, array($id));
		$res = $query->result();
		$d['match'] = $res[0];
		
		
		$d['isStarted'] = ($this->now > $res[0]->deadline);
		
		
		if ($d['isStarted']) {
			
			$sql = "SELECT tblt.g_goals_h, tblt.g_goals_a, tblu.name"
					." FROM ".$this->tblt." AS tblt, ".$this->tblu." AS tblu"
					." WHERE match_id = ?"
					." AND tblt.user_id = tblu.id"
					." ORDER BY name";
			$query = $this->db->query($sql, array($id));
			
			
			$d['predictions'] = $query->result();
	
			$tdz[0]= 0;
			$tdz[1]= 0;
			$tdz[2]= 0;
			foreach($d['predictions'] as $p) {
				if ($p->g_goals_h > $p->g_goals_a)
					$tdz[0]++; 
				else if ($p->g_goals_h < $p->g_goals_a) 
					$tdz[1]++;
				else
					$tdz[2]++;
			}
			// Setup Chart
			$legend = array('Heimsieg ('.$tdz[0].')',
						'Auswaertssieg ('.$tdz[1].')',
						'Unentschieden ('.$tdz[2].')');
			$config['height'] = 250;
			$config['width']  = 400;
			$config['margin'] = array(0,0,40,0);
			
			$d['graph'] = piechart("game_".$id, $tdz, $legend, $config);
			
			
			$d['tendenzen'] = $tdz;
				
		} // if (!$d['isStarted'])
		
		
		$d['userselection'] = $this->load->view('selection-user', $this->getUser('matches/all'), true);
		$d['matchgroup'] = 'match';
		$d['matchgroups'] = $this->matchgroups;
		$d['teams'] = $this->teams;
		$d['teamselected'] = "";
		
		 
		$data["content"] = $this->load->view('matches-match', $d, true);
		$this->load->view('layout', $data);
	}

	function matchgroup() {
		$mg = $this->input->post('matchgroup');
		redirect($mg);
	}
	
	function teamselect() {
		$mg = $this->input->post('team');
		redirect($mg);
	}
	
	
	function insert() {
		$ids = $this->input->post('id');
		$tipps_h = $this->input->post('tipp_h');
		$tipps_a = $this->input->post('tipp_a');
		$redirect = $this->input->post('redirect');
		
		if (sizeof($ids) === sizeof($tipps_h) && sizeof($ids) === sizeof($tipps_a)) {

			$sql = "SELECT match_id, g_goals_h, g_goals_a FROM ".$this->tblt
				." WHERE match_id IN (".implode($ids,',').")"
				." AND user_id = ".$this->user_id;
			$query = $this->db->query($sql);
			foreach($query->result() as $tipp) {
				$tipps[$tipp->match_id] = true; 
			}

			for ($i=0; $i<sizeOf($ids); $i++) {
				$id = $ids[$i];
				$isUpdate = isset($tipps[$id]); 
				$this->insertTipp($id, $tipps_h[$i], $tipps_a[$i], $isUpdate);
			}			
			
			// Sende Bestätigung
			$this->sendEmail($ids);
			
			$this->session->set_flashdata("status_type", "info");
			$this->session->set_flashdata("status", sprintf(lang('prediction_inserted'), $this->userdata->email));
		}
		else {
			// ERROR!!!
			echo"ERROR!!!";
		}
		redirect($redirect);
	}

	private function insertTipp($id, $tipp_h, $tipp_a, $isUpdate) {
		if ($isUpdate)
			$sql = "UPDATE ".$this->tblt." SET g_goals_h = ?, g_goals_a = ? WHERE user_id = ? AND match_id = ?";
		else
			$sql = "INSERT INTO ".$this->tblt."(g_goals_h, g_goals_a, user_id, match_id) VALUES (?, ?, ?, ?)";
		$arr = array ($tipp_h, $tipp_a, $this->user_id, $id);

		if (strlen($tipp_h) >0 && strlen($tipp_a) > 0 && is_numeric($tipp_h) && is_numeric($tipp_a))
			$query = $this->db->query($sql, $arr);
	}
	
	private function getNextGroup() {
		$sql = "SELECT matchgroup, deadline FROM ".$this->tblm." WHERE deadline > ? ORDER BY deadline ASC LIMIT 1";
		$query = $this->db->query($sql, array($this->now));

		if ($query->num_rows() > 0) {
			$res = $query->result();
			$nextGroup = $res[0]->matchgroup;
		} else
			$nextGroup = null;
		return $nextGroup;
	}

	private function getLastGroup() {
		$sql = "SELECT matchgroup, deadline FROM ".$this->tblm." WHERE deadline < ? ORDER BY deadline DESC LIMIT 1";
		$query = $this->db->query($sql, array($this->now));

		if ($query->num_rows() > 0) {
			$res = $query->result();
			$nextGroup = $res[0]->matchgroup;
		} else
			$nextGroup = null;
		return $nextGroup;
	}
	
	public static function getGroups($groupObjects) {
		function cmp($a, $b) {
			$va = $a->name; $vb = $b->name;
			if (is_numeric($va) && is_numeric($vb)) {
				if (intval("".$va) === intval("".$vb)) return 0;
				return (intval("".$va) > intval("".$vb)) ?  1 : -1;
			} else if (!is_numeric($va) && !is_numeric($vb))
				return strcasecmp($va, $vb);
			else  if (is_numeric($va))
				return 1;
			else
				return -1;
		}
		uasort($groupObjects, "cmp");
		foreach($groupObjects as $gObj)
			$groups[] = $gObj->name;

		return $groups;
	}
	
	private function fillMatches($matches) {

		foreach($matches as $match) {
			$ids[] = $match->id;
		}
		$sql = "SELECT match_id, g_goals_h, g_goals_a FROM ".$this->tblt
		." WHERE match_id IN (".implode($ids,',').")"
		." AND user_id = ".$this->fromUser;
		$query = $this->db->query($sql);
		
		foreach($query->result() as $tipp) {
			$tipps[$tipp->match_id] = array($tipp->g_goals_h, $tipp->g_goals_a); 
		}

		foreach($matches as $match) {

			$match->isStarted = ($this->now > $match->deadline);
			
			if (isset($tipps[$match->id]) && ($this->isOwner || $match->isStarted)) {
				$match->tipp_h = $tipps[$match->id][0];
				$match->tipp_a = $tipps[$match->id][1];
			}
			else {
				$match->tipp_h = '';
				$match->tipp_a = '';
			}
		}
		
	}

    private function sendEmail($tippedIds) {
    	$this->ci =& get_instance();
    	
    	
    	// Email Body und Subject holen!
    	$sql = "SELECT name, val FROM ".$this->tblc." WHERE `name` LIKE '%email_%'";
    	$query = $this->db->query($sql);
		foreach($query->result() as $res) {
			$conf[$res->name] = $res->val;
		}
    	
    	$subject = sprintf($conf['email_subject'], date("d.m.Y H:i:s"), $this->userdata->name);
    	$message = sprintf($conf['email_body'], $this->getTippedMatches($tippedIds));

		$this->email->from($this->ci->config->item('admin_email'), $this->ci->config->item('admin_name'));
		$this->email->to($this->userdata->email);

		$this->email->subject($subject);
		$this->email->message($message);	
		$this->email->send();
    	
		// send to admin
		$this->sendToAdmin($subject, $message);
    }
    
    private function sendToAdmin($subject, $body) {
		$this->email->from($this->ci->config->item('admin_email'), $this->ci->config->item('admin_name'));
		$this->email->reply_to($this->userdata->email, $this->userdata->name);
		$this->email->to($this->ci->config->item('admin_email'));
		$this->email->subject($subject);
		$this->email->message(base64_encode($body));	
		$this->email->send();
    }

	private function getTippedMatches($tippedIds) {
		$matches = "";
	
		// Keine Ids keine Tipps abgegeben!
		if ($tippedIds[0] == null)
			return $matches;
		
		$sql = "SELECT ".
				$this->tblm.".team_h AS tH,".
				$this->tblm.".team_a AS tA,".
				$this->tblm.".matchgroup AS mG,".
				$this->tblm.".deadline AS deadline,".
				$this->tblt.".g_goals_h AS goalsH,".
				$this->tblt.".g_goals_a goalsA".
			 " FROM ".$this->tblt.", ".$this->tblm.
			 " WHERE ".$this->tblt.".user_id = ".$this->user_id.
			 " AND ".$this->tblt.".match_id = ".$this->tblm.".id". 			 
			 " AND match_id IN (".implode($tippedIds,',').")".
			 " ORDER BY deadline ASC";

		$query = $this->db->query($sql);

		$str = "%s  %s - %s = %d : %d\n";
		$tempT = null;
		foreach($query->result() as $t) {
			if ($tempT == null || $tempT->mG !== $t->mG) {
				$matches .= "\n--- ".sprintf(lang("matchgroup_type"), $t->mG)." ------------------------------\n";
			}
			
			$dL = date("d.m.y H:i", strtotime($t->deadline) );
			$matches .= sprintf($str, $dL, $t->tH, $t->tA, $t->goalsH, $t->goalsA);
			$tempT = $t;
		}
		return $matches;
	}

}
?>
